/*
 * ============================================================================
 *
 *       Filename:  main.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2014年07月09日 17时29分44秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  zkk(zkk), zkk@126.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>  
#include <unistd.h>  
#include <errno.h>
#include <string.h>
#include <sys/types.h>  
#include <sys/ioctl.h>
#include <sys/file.h>
#include <fcntl.h>
#include <sys/stat.h>  
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <mosquitto.h>

#include "include/buffer.h"
#include "include/log.h"
#include "include/arg.h"
#include "include/common.h"
#include "include/mqtt_client.h"

static int one_instance()
{
	char path[BUF_SIZE] = {0};
	sprintf(path, "/var/run/realfly_heartbeat.pid");
	sys_debug("path %s\n", path);

	int pid_file = open(path, O_CREAT | O_RDWR | O_CLOEXEC, 0666);
	int rc = flock(pid_file, LOCK_EX | LOCK_NB);
	if(rc) {
		if(EWOULDBLOCK == errno) {
			sys_warn("another program is running\n");
			return -1;
		}
	}
	return 0;
}

int main(int argc, char *argv[])
{

	proc_args(argc, argv);
	if(one_instance() < 0)
		return 0;

	if(daemon_mode)
		daemon(0, 0);

reconnect:

	sys_debug("start ! ======\n");

	struct mymqtt *mymq = create_mqtt(NULL, 1, NULL);
	if(!mymq) {
		sleep(5);
		goto reconnect;
	}

	struct timeval tv;

	while(1) {
		mosquitto_publish(mymq->mosq, NULL, args_info.pubtopic_arg,
				strlen(args_info.msg_arg),
				(void*)args_info.msg_arg, 0, 0);

		tv.tv_sec = args_info.tick_arg;
		tv.tv_usec = 0;
		select(0, NULL, NULL, NULL, &tv);
	}

	mosquitto_destroy(mymq->mosq);
	mosquitto_lib_cleanup();

	sys_debug("not should run here\n");

	goto reconnect;

	return 0;
}
